package com.wochao.web.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wochao.model.entity.BrowsingHistory;
import com.wochao.web.app.mapper.BrowsingHistoryMapper;
import com.wochao.web.app.service.BrowsingHistoryService;
import com.wochao.web.app.vo.history.HistoryItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {

    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;

    /**
     * 分页查询浏览历史
     *
     * @param page
     * @param userId
     * @return
     */
    @Override
    public IPage<HistoryItemVo> pageQueryHistory(IPage<HistoryItemVo> page, Long userId) {
        return browsingHistoryMapper.pageQueryHistory(page, userId);
    }

    /**
     * 保存浏览历史
     *
     * @param userId
     * @param id
     */
    @Override
    @Async//将该方法设置为异步操作
    public void saveHistory(Long userId, Long id) {
        //判断当前用户是不是首次浏览该房间
        LambdaQueryWrapper<BrowsingHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BrowsingHistory::getUserId, userId);
        queryWrapper.eq(BrowsingHistory::getRoomId, id);
        BrowsingHistory browsingHistory = browsingHistoryMapper.selectOne(queryWrapper);

        if (browsingHistory != null) {//不是首次浏览则更新浏览时间
            Date date = new Date();
            browsingHistory.setBrowseTime(date);
            browsingHistory.setUpdateTime(date);
            browsingHistoryMapper.updateById(browsingHistory);

        } else {//首次浏览则插入新的浏览历史数据
            BrowsingHistory newBrowsingHistory = new BrowsingHistory();
            newBrowsingHistory.setUserId(userId);
            newBrowsingHistory.setRoomId(id);
            newBrowsingHistory.setBrowseTime(new Date());
            browsingHistoryMapper.insert(newBrowsingHistory);
        }

    }
}